package exploitpack;

import java.awt.Color;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author jsacco
 */
public class UpdateManager extends javax.swing.JFrame {

    private String licenseType;

    /**
     * Creates new form UpdateManager
     */
    public UpdateManager() {
        int lebar = this.getWidth() / 2;
        int tinggi = this.getHeight() / 2;
        int x = (Toolkit.getDefaultToolkit().getScreenSize().width / 2) - lebar;
        int y = (Toolkit.getDefaultToolkit().getScreenSize().height / 2) - tinggi;
        this.setLocation(x, y);
        this.setVisible(true);
        initComponents();
        setDefaultCloseOperation(ExploitWizard.DISPOSE_ON_CLOSE);
        getContentPane().setBackground(Color.WHITE);
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/exploitpack/resources/bug.png")));

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaUpdate = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Exploit Pack - Update manager");
        setResizable(false);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/about2.png"))); // NOI18N

        jButton1.setText("Close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Update");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Receive the latest updates by running this manager");

        jTextAreaUpdate.setEditable(false);
        jTextAreaUpdate.setColumns(20);
        jTextAreaUpdate.setRows(5);
        jTextAreaUpdate.setText("Running the update manager could take a few minutes...\nClick update to start.\n\n");
        jScrollPane1.setViewportView(jTextAreaUpdate);

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/updater.png"))); // NOI18N

        jLabel4.setText("Exploit Pack is configured by default to retrieve updates of modules and");

        jLabel5.setText("related files directly from the repository hosted on the offical web site.");

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/up.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel4))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel3))
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel6)
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleName("Exploit Pack - Update modules");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        Thread agentServer = new Thread("agentThread") {
            @Override
            public void run() {
                try {
                    FileReader fstream = null;
                    jProgressBar1.setMaximum(100);
                    jTextAreaUpdate.append("Establishing communication with the repository.. please wait\n");
                    fstream = new FileReader("data/config/exploitpack1");
                    BufferedReader in = new BufferedReader(fstream);
                    licenseType = in.readLine() + "\n";
                    // Close the output stream

                    in.close();
                    if (licenseType.contains("1")) {
                        jTextAreaUpdate.append("Downloading files...");

                        // First download index of module
                        try {

                            URL urlmodule = new URL("http://exploitpack.com/repository/modules/index/module.list");
                            jTextAreaUpdate.append("Contacting official server: http://exploitpack.com" + "\n");
                            jTextAreaUpdate.append("Downloading module: " + "index of modules" + "\n");
                            URLConnection urlC = urlmodule.openConnection();
                            // Copy resource to local file, use remote file
                            // if no local file name specified
                            InputStream is = urlmodule.openStream();
                            // Print info about resource
                            jTextAreaUpdate.append("Copying resource: " + urlC.getContentType() + "\n");
                            Date date = new Date(urlC.getLastModified());
                            jTextAreaUpdate.append("Modified on: " + date.toString() + "\n");
                            FileOutputStream fos = null;

                            String localFile = null;
                            // Get only file name
                            localFile = "exploits/index/" + "module.list";
                            fos = new FileOutputStream(localFile);

                            int oneChar, count = 0;
                            while ((oneChar = is.read()) != -1) {
                                fos.write(oneChar);
                                count++;
                            }
                            is.close();
                            fos.close();
                            jTextAreaUpdate.append(count + " byte(s) copied");
                            //progressBar.setSelection(10);
                        } catch (IOException e) {
                            jTextAreaUpdate.append("Error downloading module list \n");
                            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, e);
                        }
                        jProgressBar1.setValue(10);
                        // Download XML
                        try {
                            URL url = new URL("http://exploitpack.com/repository/modules/index/xml.list");
                            jTextAreaUpdate.append("Contacting official server: http://exploitpack.com" + "\n");
                            jTextAreaUpdate.append("Downloading module: " + "index of xml" + "\n");
                            URLConnection urlC = url.openConnection();
                            // Copy resource to local file, use remote file
                            // if no local file name specified
                            InputStream is = url.openStream();
                            // Print info about resource
                            jTextAreaUpdate.append("Copying resource: " + urlC.getContentType() + "\n");
                            Date date = new Date(urlC.getLastModified());
                            jTextAreaUpdate.append("Modified on: " + date.toString() + "\n");
                            FileOutputStream fos = null;

                            String localFile = null;
                            // Get only file name
                            localFile = "exploits/index/" + "xml.list";
                            fos = new FileOutputStream(localFile);

                            int oneChar, count = 0;
                            while ((oneChar = is.read()) != -1) {
                                fos.write(oneChar);
                                count++;
                            }
                            is.close();
                            fos.close();
                            jTextAreaUpdate.append(count + " byte(s) copied");
                        } catch (IOException e) {
                            jTextAreaUpdate.append("Error downloading XML");
                            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, e);
                        }
                        jProgressBar1.setValue(20);
                        // Download DATA
                        try {
                            URL url = new URL("http://exploitpack.com/repository/modules/index/data.list");
                            jTextAreaUpdate.append("Contacting official server: http://exploitpack.com" + "\n");
                            jTextAreaUpdate.append("Downloading module: " + "index of data" + "\n");
                            URLConnection urlC = url.openConnection();
                            // Copy resource to local file, use remote file
                            // if no local file name specified
                            InputStream is = url.openStream();
                            // Print info about resource
                            jTextAreaUpdate.append("Copying resource: " + urlC.getContentType() + "\n");
                            Date date = new Date(urlC.getLastModified());
                            jTextAreaUpdate.append("Modified on: " + date.toString() + "\n");
                            FileOutputStream fos = null;

                            String localFile = null;
                            // Get only file name
                            localFile = "exploits/index/" + "data.list";
                            fos = new FileOutputStream(localFile);

                            int oneChar, count = 0;
                            while ((oneChar = is.read()) != -1) {
                                fos.write(oneChar);
                                count++;
                            }
                            is.close();
                            fos.close();
                            jTextAreaUpdate.append(count + " byte(s) copied");
                        } catch (Exception e) {
                            jTextAreaUpdate.append("Error downloading data \n");
                            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, e);
                        }
                        jProgressBar1.setValue(35);

                        // Read module list and download files
                        try {
                            // Create file
                            FileInputStream fstreamfiles = new FileInputStream("exploits/index/module.list");
                            try (DataInputStream infiles = new DataInputStream(fstreamfiles)) {
                                BufferedReader br = new BufferedReader(new InputStreamReader(infiles));
                                String strLine;

                                while ((strLine = br.readLine()) != null) {
                                    // Download index of data
                                    try {
                                        URL url = new URL("http://exploitpack.com/repository/modules/code/" + strLine);
                                        jTextAreaUpdate.append("Contacting official server: http://exploitpack.com" + "\n");
                                        jTextAreaUpdate.append("Downloading module: " + strLine + "\n");
                                        URLConnection urlC = url.openConnection();
                                        // Copy resource to local file, use remote file
                                        // if no local file name specified
                                        InputStream is = url.openStream();
                                        // Print info about resource
                                        jTextAreaUpdate.append("Copying resource: " + urlC.getContentType() + "\n");
                                        Date date = new Date(urlC.getLastModified());
                                        jTextAreaUpdate.append("Modified on: " + date.toString() + "\n");
                                        FileOutputStream fos = null;

                                        String localFile = null;
                                        // Get only file name
                                        localFile = "exploits/code/" + strLine;
                                        fos = new FileOutputStream(localFile);

                                        int oneChar, count = 0;
                                        while ((oneChar = is.read()) != -1) {
                                            fos.write(oneChar);
                                            count++;
                                        }
                                        is.close();
                                        fos.close();
                                        jTextAreaUpdate.append(count + " byte(s) copied\n");
                                    } catch (IOException e1) {
                                        System.out.println(e1);
                                    }
                                }
                            }
                        } catch (IOException e) {
                            jTextAreaUpdate.append("Error downloading files  \n");
                            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, e);
                        }
                        jProgressBar1.setValue(60);

                        // Read xml list and download files
                        try {
                            // Create file
                            FileInputStream fstreamXML = new FileInputStream("exploits/index/xml.list");
                            DataInputStream inXML = new DataInputStream(fstreamXML);
                            BufferedReader br = new BufferedReader(new InputStreamReader(inXML));
                            String strLine;

                            while ((strLine = br.readLine()) != null) {
                                // Download index of data
                                URL url = new URL("http://exploitpack.com/repository/modules/" + strLine);
                                jTextAreaUpdate.append("Contacting official server: http://exploitpack.com" + "\n");
                                jTextAreaUpdate.append("Downloading xml: " + strLine + "\n");
                                URLConnection urlC = url.openConnection();
                                // Copy resource to local file, use remote file
                                // if no local file name specified
                                InputStream is = url.openStream();
                                // Print info about resource
                                jTextAreaUpdate.append("Copying resource: " + urlC.getContentType() + "\n");
                                Date date = new Date(urlC.getLastModified());
                                jTextAreaUpdate.append("Modified on: " + date.toString() + "\n");
                                FileOutputStream fos = null;

                                String localFile = null;
                                // Get only file name
                                localFile = "exploits/" + strLine;
                                fos = new FileOutputStream(localFile);

                                int oneChar, count = 0;
                                while ((oneChar = is.read()) != -1) {
                                    fos.write(oneChar);
                                    count++;
                                }
                                is.close();
                                fos.close();
                                jTextAreaUpdate.append(count + " byte(s) copied\n");
                            }
                            in.close();
                        } catch (IOException e) {
                            jTextAreaUpdate.append("Error downloading xml files  \n");
                            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, e);
                        }
                        jProgressBar1.setValue(80);

                        // Read data list and download files
                        try {
                            // Create file
                            FileInputStream fstreamList = new FileInputStream("exploits/index/data.list");
                            DataInputStream inList = new DataInputStream(fstreamList);
                            BufferedReader br = new BufferedReader(new InputStreamReader(inList));
                            String strLine;

                            while ((strLine = br.readLine()) != null) {
                                // Download index of data
                                URL url = new URL("http://exploitpack.com/repository/modules/code/data/" + strLine);
                                jTextAreaUpdate.append("Contacting official server: http://exploitpack.com" + "\n");
                                jTextAreaUpdate.append("Downloading data: " + strLine + "\n");
                                URLConnection urlC = url.openConnection();
                                // Copy resource to local file, use remote file
                                // if no local file name specified
                                InputStream is = url.openStream();
                                // Print info about resource
                                jTextAreaUpdate.append("Copying resource: " + urlC.getContentType() + "\n");
                                Date date = new Date(urlC.getLastModified());
                                jTextAreaUpdate.append("Modified on: " + date.toString() + "\n");
                                FileOutputStream fos = null;

                                String localFile = null;
                                // Get only file name
                                localFile = "exploits/code/data/" + strLine;
                                fos = new FileOutputStream(localFile);

                                int oneChar, count = 0;
                                while ((oneChar = is.read()) != -1) {
                                    fos.write(oneChar);
                                    count++;
                                }
                                is.close();
                                fos.close();
                                jTextAreaUpdate.append(count + " byte(s) copied\n");
                            }
                            // Close the output stream
                            in.close();
                        } catch (IOException e) {
                            jTextAreaUpdate.append("Error downloading list of files  \n");
                            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, e);
                        }
                        jProgressBar1.setValue(100);

                        // Finally
                        jTextAreaUpdate.append("Update process has been executed successfully. \n");
                        jButton2.setEnabled(false);
                        JOptionPane.showMessageDialog(null, "Update manager executed successfully", "Exploit Pack says:", JOptionPane.INFORMATION_MESSAGE);

                    }
                } catch (IOException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        agentServer.start();

    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UpdateManager.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UpdateManager.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UpdateManager.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UpdateManager.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UpdateManager().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTextAreaUpdate;
    // End of variables declaration//GEN-END:variables
}
